package fun.qu_an.minecraft.velocity.mgh.encoding;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.handler.codec.EncoderException;

public class StringEncoding {
	public static final int DEFAULT_MAX_STRING_LENGTH = Short.MAX_VALUE;
	public static void encode(ByteBuf buf, CharSequence string) {
		if (string.length() > DEFAULT_MAX_STRING_LENGTH) {
			throw new EncoderException("String too big (was " + string.length() + " characters, max " + DEFAULT_MAX_STRING_LENGTH + ")");
		}
		int i = ByteBufUtil.utf8MaxBytes(string);
		ByteBuf byteBuf = buf.alloc().buffer(i);
		try {
			int j = ByteBufUtil.writeUtf8(byteBuf, string);
			int k = ByteBufUtil.utf8MaxBytes(DEFAULT_MAX_STRING_LENGTH);
			if (j > k) {
				throw new EncoderException("String too big (was " + j + " bytes encoded, max " + k + ")");
			}
			while (true) {
				if ((j & 0xFFFFFF80) == 0) {
					buf.writeByte(j);
					break;
				}
				buf.writeByte(j & 0x7F | 0x80);
				j >>>= 7;
			}
			buf.writeBytes(byteBuf);
		} finally {
			byteBuf.release();
		}
	}
}
